from django.http import JsonResponse, QueryDict
from django.views import View
from kubernetes import client, config
from libs import k8s, node_data
import os,json

#节点接口
class node_api(View):

    k8s.load_auth_config()
    core_api = client.CoreV1Api()

    def get(self,request):
        search_key = request.GET.get('query')
        data = [] # [{},{},...]
        try:
            for item in self.core_api.list_node_with_http_info()[0].items:
                name = item.metadata.name
                labels = item.metadata.labels
                status = "是" if item.status.conditions[-1].status else "否"
                scheduler = "是" if item.spec.unschedulable is None else "否"
                cpu = item.status.capacity['cpu']
                memory = item.status.capacity['memory']
                kubelet_version = item.status.node_info.kubelet_version
                container_runtime_version = item.status.node_info.container_runtime_version
                create_time = k8s.timestamp_format(item.metadata.creation_timestamp)
                d = {"name": name, "labels": labels, "status": status, "scheduler": scheduler,
                     "cpu": cpu, "memory": memory, "kubelet_version": kubelet_version,
                     "container_runtime_version": container_runtime_version, "create_time": create_time}

                # 关键字查询
                if search_key:
                    if search_key in name:
                        data.append(d)
                else:
                    data.append(d)
            code = 200
            msg = '查询成功'
        except Exception as e:
            status = getattr(e, 'status')
            if status == 403:  # 400 格式错误，409 资源存在，403 没权限
                msg = '没有访问权限！'
            else:
                print(e)
                msg = '查询失败！%s' % e
            code = 500

        # 分页
        count = len(data)
        page = int(request.GET.get('pageNum', 1))  # 当前第几页
        limit = int(request.GET.get('pageSize',10))   # 当前页的数据数量
        start = (page - 1) * limit
        end = page * limit
        data = data[start:end]

        res = {'code': code, 'msg': msg, 'count': count, 'data': data}
        return JsonResponse(res)

    def delete(self,request):
        data = json.loads(request.body.decode("utf-8"))
        print(data['name'])
        code = 500
        msg = '危险操作，请使用kubectl工具删除！'
        res = {'code': code, 'msg': msg}
        return JsonResponse(res)


#命名空间接口
class namespace_api(View):

    k8s.load_auth_config()
    core_api = client.CoreV1Api()

    def get(self,request):
        search_key = request.GET.get('query')
        data = [] # [{},{},...]
        try:
            for item in self.core_api.list_namespace().items:
                name = item.metadata.name
                labels = item.metadata.labels
                status = item.status.phase
                create_time = k8s.timestamp_format(item.metadata.creation_timestamp)
                d = {"name": name, "labels": labels, "status": status, "create_time": create_time}

                # 关键字查询
                if search_key:
                    if search_key in name:
                        data.append(d)
                else:
                    data.append(d)
            code = 200
            msg = '查询成功'
        except Exception as e:
            status = getattr(e, 'status')
            if status == 403:  # 400 格式错误，409 资源存在，403 没权限
                msg = '没有访问权限！'
            else:
                print(e)
                msg = '查询失败！%s' % e
            code = 500

        # 分页
        count = len(data)
        page = int(request.GET.get('pageNum', 1))  # 当前第几页
        limit = int(request.GET.get('pageSize',10))   # 当前页的数据数量
        start = (page - 1) * limit
        end = page * limit
        data = data[start:end]

        res = {'code': code, 'msg': msg, 'count': count, 'data': data}
        return JsonResponse(res)
    def post(self,request):
       data = json.loads(request.body.decode("utf-8"))
       name = data['namespce']
       try:
           body = client.V1Namespace(
               api_version="v1",
               kind="Namespace",
               metadata=client.V1ObjectMeta(
                   name=name
               )
           )
           self.core_api.create_namespace(body=body)
           code = 200
           msg = "创建成功"
       except Exception as e:
           status = getattr(e, "status")
           if status == 403:
               msg = "没有访问权限！"
           elif status == 409:
               msg = "命名空间已存在！"
           else:
               msg = "服务器处理失败！%s" %e
           code = 500
       res = {'code': code, 'msg': msg}
       return JsonResponse(res)
    def delete(self,request):
        data = json.loads(request.body.decode("utf-8"))
        name = data['name']
        try:
            self.core_api.delete_namespace(name=name)
            code = 200
            msg = '删除成功'
        except Exception as e:
            status = getattr(e, 'status')
            if status == 403:  # 400 格式错误，409 资源存在，403 没权限
                msg = '没有访问权限！'
            else:
                print(e)
                msg = '删除失败！%s' % e
            code = 500
        res = {'code': code, 'msg': msg}
        return JsonResponse(res)


#所有命名空间接口
class namespace_all_api(View):

    k8s.load_auth_config()
    core_api = client.CoreV1Api()

    def get(self,request):
        data = []
        try:
            for item in self.core_api.list_namespace().items:
                name = item.metadata.name
                data.append(name)
            code = 200
            msg = '查询成功'
        except Exception as e:
            status = getattr(e, 'status')
            if status == 403:  # 400 格式错误，409 资源存在，403 没权限
                msg = '没有访问权限！'
            else:
                print(e)
                msg = '查询失败！%s' %e
            code = 500
        res = {'code': code, 'msg': msg, 'data': data}
        return JsonResponse(res)


class namespace_pod_api(View):

    k8s.load_auth_config()
    core_api = client.CoreV1Api()

    def get(self,request):
        namespace_data = []
        pod_data = []
        try:
            for item in self.core_api.list_namespace().items:
                name = item.metadata.name
                pod_count = len(self.core_api.list_namespaced_pod(namespace=name).items)
                namespace_data.append(name)
                pod_data.append(pod_count)
            code = 200
            msg = '查询成功'
        except Exception as e:
            status = getattr(e, 'status')
            if status == 403:  # 400 格式错误，409 资源存在，403 没权限
                msg = '没有访问权限！'
            else:
                print(e)
                msg = '查询失败！%s' %e
            code = 500
        res = {'code': code, 'msg': msg, 'namespace_data': namespace_data, 'pod_data': pod_data}
        return JsonResponse(res)




class node_details(View):

    k8s.load_auth_config()
    core_api = client.CoreV1Api()

    def get(self,request):
        try:
            node_name = request.GET.get('node_name')
            node_info = node_data.node_info(self.core_api, node_name)
            node_resource = node_data.node_resource(self.core_api, node_name)
            data = {"node_info": node_info, "node_resource": node_resource}
            code = 200
            msg = '获取成功'
            res = {"code": code, "msg": msg, "data": data}
            return JsonResponse(res)
        except Exception as e:
            code = 500
            msg = '获取失败：%s'%e
            print(e,123)
            res = {"code": code, "msg": msg}
            return JsonResponse(res)


class node_details_pod_list(View):

    k8s.load_auth_config()
    core_api = client.CoreV1Api()

    def get(self,request):
        print(request.GET,123)
        node_name = request.GET.get('node_name')
        data = []
        try:
            for pod in self.core_api.list_pod_for_all_namespaces().items:
                name = pod.spec.node_name
                pod_name = pod.metadata.name
                namespace = pod.metadata.namespace
                status = ("运行中" if pod.status.conditions[-1].status else "异常")
                host_network = pod.spec.host_network
                pod_ip = ("主机网络" if host_network else pod.status.pod_ip)
                create_time = k8s.timestamp_format(pod.metadata.creation_timestamp)

                if name == node_name:
                    if len(pod.spec.containers) == 1:
                        cpu_requests = "0"
                        cpu_limits = "0"
                        memory_requests = "0"
                        memory_limits = "0"
                        for c in pod.spec.containers:
                            # c_name = c.name
                            # c_image= c.image
                            cpu_requests = "0"
                            cpu_limits = "0"
                            memory_requests = "0"
                            memory_limits = "0"
                            if c.resources.requests is not None:
                                if "cpu" in c.resources.requests:
                                    cpu_requests = c.resources.requests["cpu"]
                                if "memory" in c.resources.requests:
                                    memory_requests = c.resources.requests["memory"]
                            if c.resources.limits is not None:
                                if "cpu" in c.resources.limits:
                                    cpu_limits = c.resources.limits["cpu"]
                                if "memory" in c.resources.limits:
                                    memory_limits = c.resources.limits["memory"]
                    else:
                        c_r = "0"
                        c_l = "0"
                        m_r = "0"
                        m_l = "0"
                        cpu_requests = ""
                        cpu_limits = ""
                        memory_requests = ""
                        memory_limits = ""
                        for c in pod.spec.containers:
                            c_name = c.name
                            # c_image= c.image
                            if c.resources.requests is not None:
                                if "cpu" in c.resources.requests:
                                    c_r = c.resources.requests["cpu"]
                                if "memory" in c.resources.requests:
                                    m_r = c.resources.requests["memory"]
                            if c.resources.limits is not None:
                                if "cpu" in c.resources.limits:
                                    c_l = c.resources.limits["cpu"]
                                if "memory" in c.resources.limits:
                                    m_l = c.resources.limits["memory"]

                            cpu_requests += "%s=%s<br>" % (c_name, c_r)
                            cpu_limits += "%s=%s<br>" % (c_name, c_l)
                            memory_requests += "%s=%s<br>" % (c_name, m_r)
                            memory_limits += "%s=%s<br>" % (c_name, m_l)

                    pod = {"pod_name": pod_name, "namespace": namespace, "status": status, "pod_ip": pod_ip,
                           "cpu_requests": cpu_requests, "cpu_limits": cpu_limits, "memory_requests": memory_requests,
                           "memory_limits": memory_limits, "create_time": create_time}
                    data.append(pod)

            count = len(data)

            page = int(request.GET.get('pageNum', 1))  # 当前第几页
            limit = int(request.GET.get('pageSize', 10))  # 当前页的数据数量
            start = (page - 1) * limit  # 切片的起始值
            end = page * limit  # 切片的末值
            data = data[start:end]  # 返回指定数据范围

            code = 200
            msg = "获取数据成功"
            res = {"code": code, "msg": msg, "count": count, "data": data}
        except Exception as e:
            code = 500
            msg = "获取数据失败：%s"%e
            res = {"code": code, "msg": msg}
        return JsonResponse(res)


class node_resource(View):
    k8s.load_auth_config()
    core_api = client.CoreV1Api()
    def get(self,request):
        try:
            data = node_data.node_resource(self.core_api)
            code = 200
            msg = '获取成功'
            res = {"code": code, "msg": msg, "data": data}
        except Exception as e:
            code = 500
            msg = '获取失败：%s'%e
            res = {"code": code, "msg": msg}
        return JsonResponse(res)


class pv_resource(View):
    k8s.load_auth_config()
    core_api = client.CoreV1Api()
    def get(self,request):
        try:
            pv_list = []
            for pv in self.core_api.list_persistent_volume().items:
                pv_name = pv.metadata.name
                capacity = pv.spec.capacity["storage"]  # 返回字典对象
                access_modes = pv.spec.access_modes
                reclaim_policy = pv.spec.persistent_volume_reclaim_policy
                status = pv.status.phase
                if pv.spec.claim_ref is not None:
                    pvc_ns = pv.spec.claim_ref.namespace
                    pvc_name = pv.spec.claim_ref.name
                    claim = "%s/%s" % (pvc_ns, pvc_name)
                else:
                    claim = "未关联PVC"
                storage_class = pv.spec.storage_class_name
                create_time = k8s.timestamp_format(pv.metadata.creation_timestamp)

                data = {"pv_name": pv_name, "capacity": capacity, "access_modes": access_modes,
                        "reclaim_policy": reclaim_policy, "status": status,
                        "claim": claim, "storage_class": storage_class, "create_time": create_time}
                pv_list.append(data)
            code = 200
            msg = '获取成功'
            res = {"code": code, "msg": msg, "data": pv_list}
        except Exception as e:
            code = 500
            msg = '获取失败：%s'%e
            res = {"code": code, "msg": msg}
        return JsonResponse(res)

